from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from typing import List
from pydantic import BaseModel
import time
from datetime import timedelta
from ..core.database import get_db
from ..models.product import Product
from ..models.store import Store
from ..models.group_buy_order import GroupBuyOrder
from ..models.user_order import UserOrder
from ..models.user import User
from ..models.stored_value_card import StoredValueCard

router = APIRouter(prefix="/api", tags=["group-buy"])

class JoinGroupBuyRequest(BaseModel):
    phone: str
    shares: int = 1

@router.get("/group-buy/{group_buy_id}")
async def get_group_buy_detail(group_buy_id: int, db: Session = Depends(get_db)):
    """获取拼购详情"""
    try:
        # 获取拼购信息
        group_buy = db.query(GroupBuyOrder).filter(GroupBuyOrder.id == group_buy_id).first()
        if not group_buy:
            raise HTTPException(status_code=404, detail="拼购活动不存在")
            
        # 获取商品信息
        product = db.query(Product).filter(Product.id == group_buy.product_id).first()
        if not product:
            raise HTTPException(status_code=404, detail="商品不存在")
            
        # 获取店铺信息
        store = db.query(Store).filter(Store.id == product.store_id).first()
        if not store:
            raise HTTPException(status_code=404, detail="店铺不存在")
            
        # 获取参与记录
        participants = []
        user_orders = db.query(UserOrder).filter(
            UserOrder.group_buy_order_id == group_buy_id
        ).all()
        
        for order in user_orders:
            user = db.query(User).filter(User.id == order.user_id).first()
            if user:
                participants.append({
                    "id": order.id,
                    "nickname": user.nickname or f"用户{user.phone[-4:]}",
                    "avatar": user.avatar_url or "/images/avatars/user1_avatar.jpg",
                    "joinTime": order.created_at
                })
        
        return {
            "id": group_buy.id,
            "soldShares": group_buy.sold_shares,
            "totalShares": group_buy.total_shares,
            "startTime": group_buy.start_time,
            "duration": 24 * 60 * 60 * 1000,  # 24小时，单位毫秒
            "product": {
                "id": product.id,
                "name": product.name,
                "images": product.images if isinstance(product.images, list) else [img.strip() for img in product.images.split(',') if product.images and img.strip()],
                "originalPrice": float(product.original_price) if product.original_price else 0,
                "groupBuyPrice": float(product.group_buy_price) if product.group_buy_price else 0,
                "storeName": store.name,
                "storeLogo": store.logo_url or "/images/stores/default_logo.jpg"
            },
            "participants": participants
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取拼购详情失败: {str(e)}")

@router.post("/group-buy/{group_buy_id}/join")
async def join_group_buy(group_buy_id: int, request: JoinGroupBuyRequest, db: Session = Depends(get_db)):
    """参与拼购"""
    try:
        phone = request.phone
        shares = request.shares if hasattr(request, 'shares') and request.shares else 1
        if shares < 1:
            raise HTTPException(status_code=400, detail="参与份数必须大于0")
        # 获取拼购信息
        group_buy = db.query(GroupBuyOrder).filter(GroupBuyOrder.id == group_buy_id).first()
        if not group_buy:
            raise HTTPException(status_code=404, detail="拼购活动不存在")
        # 检查拼购状态
        if group_buy.status != 1:
            raise HTTPException(status_code=400, detail="拼购活动已结束")
        # 检查是否已满员
        remaining = group_buy.total_shares - group_buy.sold_shares
        if remaining <= 0:
            raise HTTPException(status_code=400, detail="拼购已满员")
        if shares > remaining:
            raise HTTPException(status_code=400, detail=f"最多可参与{remaining}份")
        # 检查用户是否存在
        user = db.query(User).filter(User.phone == phone).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        # 获取商品信息
        product = db.query(Product).filter(Product.id == group_buy.product_id).first()
        if not product:
            raise HTTPException(status_code=404, detail="商品不存在")
        # 计算单份价格
        unit_price = product.group_buy_price / group_buy.total_shares
        
        # 创建用户订单
        user_order = UserOrder(
            user_id=user.id,
            group_buy_order_id=group_buy_id,
            product_id=product.id,
            order_no=f"GB{group_buy_id}_{user.id}_{int(time.time())}",
            shares=shares,
            total_amount=unit_price * shares
        )
        db.add(user_order)
        # 更新拼购进度
        group_buy.sold_shares += shares
        # 检查是否成团
        if group_buy.sold_shares >= group_buy.total_shares:
            group_buy.status = 2  # 拼购成功
            
            # 为所有参与用户生成储值卡（按用户合并计算）
            all_orders = db.query(UserOrder).filter(
                UserOrder.group_buy_order_id == group_buy_id
            ).all()
            
            # 按用户ID分组，计算每个用户的总参与份数
            user_shares = {}
            for order in all_orders:
                if order.user_id not in user_shares:
                    user_shares[order.user_id] = 0
                user_shares[order.user_id] += order.shares
            
            # 为每个用户生成一张合并的储值卡
            for user_id, total_shares in user_shares.items():
                # 计算该用户的总储值卡金额
                card_amount = (product.group_buy_price / group_buy.total_shares) * total_shares
                
                # 检查是否已存在该用户和该商品的储值卡
                existing_card = db.query(StoredValueCard).filter(
                    StoredValueCard.user_id == user_id,
                    StoredValueCard.product_id == product.id
                ).first()
                
                if existing_card:
                    # 如果已存在，更新金额
                    existing_card.original_amount += card_amount
                    existing_card.current_amount += card_amount
                    print(f"更新用户 {user_id} 的储值卡，增加金额 {card_amount}")
                else:
                    # 如果不存在，创建新的储值卡
                    stored_value_card = StoredValueCard(
                        user_id=user_id,
                        product_id=product.id,
                        store_id=product.store_id,
                        card_number=f"SV{int(time.time())}{user_id}{group_buy_id}",
                        original_amount=card_amount,
                        current_amount=card_amount,
                        status=1,  # 正常状态
                        valid_until=func.now() + timedelta(days=365)  # 有效期1年
                    )
                    db.add(stored_value_card)
                    print(f"为用户 {user_id} 创建新储值卡，金额 {card_amount}")
        db.commit()
        return {
            "success": True,
            "message": "参与成功",
            "orderId": user_order.id
        }
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"参与拼购失败: {str(e)}") 